package com.dou361.ijkplayer.widget;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dou361.ijkplayer.R;
import com.dou361.ijkplayer.adapter.StreamSelectAdapter;
import com.dou361.ijkplayer.bean.VideoijkBean;
import com.dou361.ijkplayer.listener.OnControlPanelVisibilityChangeListener;
import com.dou361.ijkplayer.listener.OnKeyListener;
import com.dou361.ijkplayer.listener.OnPlayerBackListener;
import com.dou361.ijkplayer.listener.OnShowThumbnailListener;
import com.dou361.ijkplayer.utils.KeybordS;
import com.dou361.ijkplayer.utils.NetworkUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.hdodenhof.circleimageview.CircleImageView;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;


/**
 * ========================================
 * <p>
 * 版 权：dou361.com 版权所有 （C） 2015
 * <p>
 * 作 者：陈冠明
 * <p>
 * 个人网站：http://www.dou361.com
 * <p>
 * 版 本：1.0
 * <p>
 * 创建日期：2016/4/14
 * <p>
 * 描 述：
 * <p>
 * <p>
 * 修订历史：
 * <p>
 * ========================================
 */
public class PlayerView implements OnKeyListener,HeartViewGroup.CompleteAnimListener,View.OnTouchListener{

    /**
     * 打印日志的TAG
     */
    private static final String TAG = PlayerView.class.getSimpleName();
    /**
     * 全局上下文
     */
    private  Context mContext;
    /**
     * 依附的容器Activity
     */
    private final Activity mActivity;
    /**
     * Activity界面的中布局的查询器
     */
    private final LayoutQuery query;
    /**
     * 原生的Ijkplayer
     */
    private final IjkVideoView videoView;
    /**
     * 播放器整个界面
     */
    private final View rl_box;
    /**
     * 播放器顶部控制bar
     */
    private final View ll_topbar;
    /**
     * 播放器底部控制bar
     */
    private final View ll_bottombar;
    /**
     * 播放器封面，播放前的封面或者缩列图
     */
    private final ImageView iv_trumb;


    /**
     * 视频返回按钮
     */
    private final ImageView videoBackImg;
    /**
     * 主播关注按钮
     */
    private final TextView videoAttention;
    private final CircleImageView videoHeadImg;
    private final RelativeLayout videoAttentionRela;
    /**
     * 用户举报按钮
     */
    private final ImageView videoReportImg;
    private final TextView videoReportTv;
    private final RelativeLayout videoReportRela;
    /**
     * 用户收藏按钮
     */
    private final ImageView videoLikeImg;
    private final TextView videoLikeTv;
    private final RelativeLayout videoLikeRela;
    /**
     * 用户转发按钮
     */
    private final ImageView videoTransmitImg;
    private final TextView videoTransmitTv;
    private final RelativeLayout videoTransmitRela;
    /**
     * 用户打赏按钮
     */
    private final ImageView videoRewardImg;
    private final TextView videoRewardTv;
    private final RelativeLayout videoReward;
    private final ImageView videoCommentImg;
    private final TextView videoCommentTv;
    private final RelativeLayout videoCommentRela;
    private final ImageView videoAddImg;
    private final HeartRela videoPause;
    /**
     * 视频中间的播放按钮
     */
    private final ImageView videoPlayIcon;
    /**
     * 不同分辨率的适配器
     */
    private final StreamSelectAdapter streamSelectAdapter;
    /**
     * 码流列表
     */
    private List<VideoijkBean> listVideos = new ArrayList<VideoijkBean>();

    /**
     * 当前状态
     */
    private int status = PlayStateParams.STATE_IDLE;
    /**
     * 当前播放位置
     */
    private int currentPosition;
    /**
     * 滑动进度条得到的新位置，和当前播放位置是有区别的,newPosition =0也会调用设置的，故初始化值为-1
     */
    private long newPosition = -1;
    /**
     * 视频旋转的角度，默认只有0,90.270分别对应向上、向左、向右三个方向
     */
    private int rotation = 0;
    /**
     * 视频显示比例,默认保持原视频的大小
     */
    private int currentShowType = PlayStateParams.fitparent;
    /**
     * 播放总时长
     */
    private long duration;
    /**
     * 当前声音大小
     */
    private int volume;
    /**
     * 设备最大音量
     */
    private final int mMaxVolume;
    /**
     * 获取当前设备的宽度
     */
    private final int screenWidthPixels;
    /**
     * 记录播放器竖屏时的高度
     */
    private final int initHeight;
    /**
     * 当前亮度大小
     */
    private float brightness;
    /**
     * 当前播放地址
     */
    private String currentUrl;
    /**
     * 当前选择的视频流索引
     */
    private int currentSelect;
    /**
     * 记录进行后台时的播放状态0为播放，1为暂停
     */
    private int bgState;
    /**
     * 自动重连的时间
     */
    private int autoConnectTime = 5000;
    /**
     * 第三方so是否支持，默认不支持，true为支持
     */
    private boolean playerSupport;
    /**
     * 是否是直播 默认为非直播，true为直播false为点播，根据isLive()方法前缀rtmp或者后缀.m3u8判断得出的为直播，比较片面，有好的建议欢迎交流
     */
    private boolean isLive;
    /**
     * 是否显示控制面板，默认为隐藏，true为显示false为隐藏
     */
    private boolean isShowControlPanl;
    /**
     * 禁止触摸，默认可以触摸，true为禁止false为可触摸
     */
    private boolean isForbidTouch;
    /**
     * 当前是否切换视频流，默认为否，true是切换视频流，false没有切换
     */
    private boolean isHasSwitchStream;
    /**
     * 是否在拖动进度条中，默认为停止拖动，true为在拖动中，false为停止拖动
     */
    private boolean isDragging;
    /**
     * 播放的时候是否需要网络提示，默认显示网络提示，true为显示网络提示，false不显示网络提示
     */
    private boolean isGNetWork = true;

    private boolean isCharge;
    private int maxPlaytime;
    /**
     * 是否只有全屏，默认非全屏，true为全屏，false为非全屏
     */
    private boolean isOnlyFullScreen;
    /**
     * 是否禁止双击，默认不禁止，true为禁止，false为不禁止
     */
    private boolean isForbidDoulbeUp;
    /**
     * 是否出错停止播放，默认是出错停止播放，true出错停止播放,false为用户点击停止播放
     */
    private boolean isErrorStop = true;
    /**
     * 是否是竖屏，默认为竖屏，true为竖屏，false为横屏
     */
    private boolean isPortrait = true;
    /**
     * 是否隐藏中间播放按钮，默认不隐藏，true为隐藏，false为不隐藏
     */
    private boolean isHideCenterPlayer;
    /**
     * 是否自动重连，默认5秒重连，true为重连，false为不重连
     */
    private boolean isAutoReConnect = true;
    /**
     * 是否隐藏topbar，true为隐藏，false为不隐藏
     */
    private boolean isHideTopBar;
    /**
     * 音频管理器
     */
    private final AudioManager audioManager;


    /**
     * 同步进度
     */
    private static final int MESSAGE_SHOW_PROGRESS = 1;
    /**
     * 设置新位置
     */
    private static final int MESSAGE_SEEK_NEW_POSITION = 3;
    /**
     * 隐藏提示的box
     */
    private static final int MESSAGE_HIDE_CENTER_BOX = 4;
    /**
     * 重新播放
     */
    private static final int MESSAGE_RESTART_PLAY = 5;
    /**
     * 单击事件
     */
    private static final int MESSAGE_ONSINGLE_CLICK=6;
    /**
     * 双击事件
     */
    private static final int MESSAGE_ONDOUBLE_CLICK=7;
    /**
     * 当前用户是否关注主播状态
     */
    private boolean isAttentionStatus;
    private TextView simpleTvCancle;
    private TextView simpleTvReport;
    private ListView simpleList;
    private int index ;
    private HashMap<Integer,TextView>map=new HashMap<>();
    //获取当前用户的喜好
    private boolean isLike;


    /**
     * 消息处理
     */
    @SuppressWarnings("HandlerLeak")
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //滑动完成，隐藏滑动提示的box
                case MESSAGE_HIDE_CENTER_BOX:
                    query.id(R.id.app_video_volume_box).gone();
                    query.id(R.id.app_video_brightness_box).gone();
                    query.id(R.id.app_video_fastForward_box).gone();
                    break;
                //滑动完成，设置播放进度
                case MESSAGE_SEEK_NEW_POSITION:
                    if (!isLive && newPosition >= 0) {
                        videoView.seekTo((int) newPosition);
                        newPosition = -1;
                    }
                    break;
                //重新去播放
                case MESSAGE_RESTART_PLAY:
                    status = PlayStateParams.STATE_ERROR;
                    startPlay();
                    updatePausePlay();
                    break;
                case MESSAGE_ONSINGLE_CLICK:
                    pausePlaying();
                    break;
                case MESSAGE_ONDOUBLE_CLICK:
                   MotionEvent e= (MotionEvent) msg.obj;
                    toggleFullScreen(e);
                    break;
            }
        }
    };

    /**========================================视频的监听方法==============================================*/

    /**
     * 控制面板收起或者显示的轮询监听
     */
    private AutoPlayRunnable mAutoPlayRunnable = new AutoPlayRunnable();
    /**
     * 控制面板显示或隐藏监听
     */
    private OnControlPanelVisibilityChangeListener onControlPanelVisibilityChangeListener;
    /**
     * 视频封面显示监听
     */
    private OnShowThumbnailListener mOnShowThumbnailListener;
    /**
     * 视频的返回键监听
     */
    private OnPlayerBackListener mPlayerBack;
    /**
     * 视频播放时信息回调
     */
    private IMediaPlayer.OnInfoListener onInfoListener;
    /**
     * 设置当前的播放状态
     */
     private boolean isPlaying;
    /**
     * 设置当前的评论弹出框是否弹出
     */
    private boolean isPopUp;
    private  final Timer timer = new Timer();
    private View bottomView;
    private EditText bottomBarEt;
    private ImageView bottomBarCancle;
    private SlideBottomEdit slide;
    private EditText shapeEt;
    long mLastTime=0;
    long mCurTime=0;


    /**
     * 点击事件监听
     */
    private final View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(v.getId()==R.id.video_head_img||v.getId() ==  R.id.video_attention_rela||v.getId() ==R.id.video_add_img ||v.getId() == R.id.video_tv_add ) {
                /**菜单*/
                showMenu();
            }  else if (v.getId() == R.id.app_video_finish) {
                /**返回*/
                if (!isOnlyFullScreen && !isPortrait) {
                    mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    if (mPlayerBack != null) {
                        mPlayerBack.onPlayerBack();
                    } else {
                        mActivity.finish();
                    }
                }
            } else if (v.getId() == R.id.app_video_netTie_icon) {
                /**使用移动网络提示继续播放*/
                isGNetWork = false;
                hideStatusUI();
                startPlay();
                //updatePausePlay();
            }else if(v.getId()==R.id.bottombar_img_report||v.getId()==R.id.bottombar_rela_report||v.getId()==R.id.bottombar_tv_report){
                //点击举报按钮时
                final AlertDialog alertDialog=new AlertDialog.Builder(mActivity).create();
                View view= View.inflate(mActivity,R.layout.simple_alertdailog,null);
                //初始化按钮
                initView(view);
                alertDialog.show();
                alertDialog.getWindow().setContentView(view);

                simpleTvCancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
                simpleTvReport.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //提交举报内容

                    }
                });


            }else if(v.getId()==R.id.bottombar_rela_like||v.getId()==R.id.bottombar_img_like||v.getId()==R.id.bottombar_tv_like){
                //选择喜欢按钮
                selectLikeButton();
            }else if(v.getId()==R.id.bottombar_rela_comment||v.getId()==R.id.bottombar_img_comment||v.getId()==R.id.bottombar_tv_comment){
                //下方的view弹出
                setAnim();



            }else if(v.getId()==R.id.bottombar_rela_transmit||v.getId()==R.id.bottombar_img_transmit||v.getId()==R.id.bottombar_tv_transmit){
                //点击转发功能
                selectTransmit();
            }else if(v.getId()==R.id.popup_cancle_img){
                isPopUp=true;
                setAnim();
            }else if (v.getId()==R.id.popup_comment_et){
                timer.schedule(new TimerTask() {
                    public void run() {
                        //调用键盘
                        KeybordS.openKeybord(shapeEt,mActivity);

                    }
                }, 200);
                if(slide!=null){
                    slide.showPopupWindow();
                }else {
                    selectComment();
                }
                slide.judgeKeybord(mContext);
            }else if(v.getId()==R.id.bottombar_img_reward||v.getId()==R.id.bottombar_rela_reward||v.getId()==R.id.bottombar_tv_reward){
                /**
                 * 点击打赏按钮
                 */
                selectReward();
            }

        }
    };
    private HeartViewGroup mHeartGroup;
    private ImageView playIcon;


    //视频播放和暂停
    private void pausePlaying() {

        if (videoView.isPlaying()) {
            isPlaying=false;
            if (isLive) {
                videoView.stopPlayback();
            } else {
                pausePlay();
            }
        } else {
            isPlaying=true;
            startPlay();
            if (videoView.isPlaying()) {
                /**ijkplayer内部的监听没有回调，只能手动修改状态*/
                status = PlayStateParams.STATE_PREPARING;
                hideStatusUI();
            }
        }
       //addView(isPlaying);
        videoPlayIcon.setVisibility(isPlaying?View.GONE:View.VISIBLE);
        updatePausePlay();
    }
    //添加暂停按钮
    private void addView(boolean isPlaying) {

        if(isPlaying){
            if(playIcon!=null){
                videoPause.removeView(playIcon);
            }
        }else {
            playIcon = new ImageView(mActivity);
            playIcon.setImageResource(R.drawable.simple_player_center_play);
            playIcon.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            videoPause.addView(playIcon);


        }
    }

    //点击打赏按钮
    private void selectReward() {
        SlideBottomReward reward=new SlideBottomReward(mActivity);
        reward.showPopupWindow();

    }

    //设置底部的view弹出的动画
    private void setAnim() {
        if(isPopUp){
            Animation animation = AnimationUtils.loadAnimation(mActivity, R.anim.pop_exit_anim);
            bottomView.startAnimation(animation);
            bottomView.setVisibility(View.GONE);
            videoPause.setVisibility(View.VISIBLE);
            isPopUp=false;
        }else {
            Animation animation = AnimationUtils.loadAnimation(mActivity, R.anim.pop_enter_anim);
            bottomView.startAnimation(animation);
            bottomView.setVisibility(View.VISIBLE);
            videoPause.setVisibility(View.GONE);
            isPopUp=true;
            
        }

    }





    //点击转发按钮
    private void selectTransmit() {
        SlideBottomShare share=new SlideBottomShare(mActivity);
        share.showPopupWindow();

    }

    //点击评论按钮
    private void selectComment() {
        if(slide==null){
            slide = new SlideBottomEdit((Activity) mContext);
        }
        slide.setInputMethodReplace();
        slide.showPopupWindow();

        //获取输入框
        shapeEt = slide.getEditText();
        //设置点击监听事件
        shapeEt.setOnClickListener(onClickListener);



    }
    //选择喜欢按钮
    private void selectLikeButton() {
        if (isLike){
            videoLikeImg.setImageResource(R.drawable.like_pressed);
            addLike();
            isLike=false;
        }else {
            videoLikeImg.setImageResource(R.drawable.like);
            reduceLike();
            isLike=true;
        }
    }
    //取消喜欢
    private void reduceLike() {
    }

    //提交用户喜好
    private void addLike() {
    }


    //初始化控件
    private void initView(View view) {
        simpleTvCancle = view.findViewById(R.id.simple_tv_cancle);
        simpleTvReport = view.findViewById(R.id.simple_tv_report);
        simpleList = view.findViewById(R.id.simple_list);
        //适配数据
        setAdapter();
    }
    //适配数据
    private void setAdapter() {
        Resources resources = mActivity.getResources();
        String[] array = resources.getStringArray(R.array.report);
        ArrayAdapter<String>arrayAdapter=new ArrayAdapter<String>(mActivity,R.layout.list_item,array);
        simpleList.setAdapter(arrayAdapter);
        simpleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(map.get(index)==null){
                    TextView simpleTvItem=view.findViewById(R.id.item_tv_detail);
                    simpleTvItem.setTextColor(Color.parseColor("#f23a58"));
                    index=i;
                    map.put(i,simpleTvItem);
                }else {
                    TextView textView = map.get(index);
                    textView.setTextColor(Color.WHITE);
                    map.remove(index);
                    TextView simpleTvItem=view.findViewById(R.id.item_tv_detail);
                    simpleTvItem.setTextColor(Color.parseColor("#f23a58"));
                    index=i;
                    map.put(i,simpleTvItem);
                }


            }
        });
    }




   //音量
    public void setBrightness(int value) {
        android.view.WindowManager.LayoutParams layout = this.mActivity.getWindow().getAttributes();
        if (brightness < 0) {
            brightness = mActivity.getWindow().getAttributes().screenBrightness;
            if (brightness <= 0.00f) {
                brightness = 0.50f;
            } else if (brightness < 0.01f) {
                brightness = 0.01f;
            }
        }
        if (value < 1) {
            value = 1;
        }
        if (value > 100) {
            value = 100;
        }
        layout.screenBrightness = 1.0F * (float) value / 100.0F;
        if (layout.screenBrightness > 1.0f) {
            layout.screenBrightness = 1.0f;
        } else if (layout.screenBrightness < 0.01f) {
            layout.screenBrightness = 0.01f;
        }
        this.mActivity.getWindow().setAttributes(layout);
    }




    /**
     * ========================================视频的监听方法==============================================
     */
    private float mInitialMotionX;
    private float mInitialMotionY;
    private Class secActivity;
    private Class thiActivity;
    /**
     * 保留旧的调用方法
     */
    public PlayerView(Activity activity) {
        this(activity, null);
    }

    /**
     * 新的调用方法，适用非Activity中使用PlayerView，例如fragment、holder中使用
     */
    public PlayerView(Activity activity, View rootView) {
        this.mActivity = activity;
        this.mContext=activity;
        try {
            IjkMediaPlayer.loadLibrariesOnce(null);
            IjkMediaPlayer.native_profileBegin("libijkplayer.so");
            playerSupport = true;
        } catch (Throwable e) {
            Log.e(TAG, "loadLibraries error", e);
        }
        screenWidthPixels = mContext.getResources().getDisplayMetrics().widthPixels;
        audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if (rootView == null) {
            query = new LayoutQuery(mActivity);
            rl_box = mActivity.findViewById(R.id.app_video_box);
            videoView =  mActivity.findViewById(R.id.video_view);
        } else {
            query = new LayoutQuery(mActivity, rootView);
            rl_box = rootView.findViewById(R.id.app_video_box);
            videoView = rootView.findViewById(R.id.video_view);
        }

        try {
            int e = Settings.System.getInt(this.mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            float progress = 1.0F * (float) e / 255.0F;
            android.view.WindowManager.LayoutParams layout = this.mActivity.getWindow().getAttributes();
            layout.screenBrightness = progress;
            mActivity.getWindow().setAttributes(layout);
        } catch (Settings.SettingNotFoundException var7) {
            var7.printStackTrace();
        }
        if (rootView == null) {
            videoPlayIcon = mActivity.findViewById(R.id.play_icon);
            videoAddImg = mActivity.findViewById(R.id.video_add_img);
            videoBackImg = mActivity.findViewById(R.id.app_video_finish);
            videoAttention = mActivity.findViewById(R.id.video_tv_add);
            videoHeadImg = mActivity.findViewById(R.id.video_head_img);
            videoAttentionRela = mActivity.findViewById(R.id.video_attention_rela);
            videoReportImg = mActivity.findViewById(R.id.bottombar_img_report);
            videoReportTv = mActivity.findViewById(R.id.bottombar_tv_report);
            videoReportRela = mActivity.findViewById(R.id.bottombar_rela_report);
            videoLikeImg = mActivity.findViewById(R.id.bottombar_img_like);
            videoLikeTv = mActivity.findViewById(R.id.bottombar_tv_like);
            videoLikeRela = mActivity.findViewById(R.id.bottombar_rela_like);
            videoTransmitImg = mActivity.findViewById(R.id.bottombar_img_transmit);
            videoTransmitTv = mActivity.findViewById(R.id.bottombar_tv_transmit);
            videoTransmitRela = mActivity.findViewById(R.id.bottombar_rela_transmit);
            videoRewardImg = mActivity.findViewById(R.id.bottombar_img_reward);
            videoRewardTv = mActivity.findViewById(R.id.bottombar_tv_reward);
            videoReward = mActivity.findViewById(R.id.bottombar_rela_reward);
            videoCommentImg = mActivity.findViewById(R.id.bottombar_img_comment);
            videoCommentTv = mActivity.findViewById(R.id.bottombar_tv_comment);
            videoCommentRela = mActivity.findViewById(R.id.bottombar_rela_comment);
            ll_topbar = mActivity.findViewById(R.id.app_video_top_box);
            ll_bottombar = mActivity.findViewById(R.id.ll_bottom_bar);
            iv_trumb = mActivity.findViewById(R.id.iv_trumb);
            videoPause = mActivity.findViewById(R.id.video_pause_rela);
            bottomView = mActivity.findViewById(R.id.popup_rela);
            bottomBarEt = mActivity.findViewById(R.id.popup_comment_et);
            bottomBarCancle = mActivity.findViewById(R.id.popup_cancle_img);
            mHeartGroup=mActivity.findViewById(R.id.heart_group);
        } else {
            Context context = rootView.getContext();
            this.mContext=context;
            videoPlayIcon = rootView.findViewById(R.id.play_icon);
            videoAddImg = rootView.findViewById(R.id.video_add_img);
            videoBackImg = rootView.findViewById(R.id.app_video_finish);
            videoAttention = rootView.findViewById(R.id.video_tv_add);
            videoHeadImg = rootView.findViewById(R.id.video_head_img);
            videoAttentionRela = rootView.findViewById(R.id.video_attention_rela);
            videoReportImg = rootView.findViewById(R.id.bottombar_img_report);
            videoReportTv = rootView.findViewById(R.id.bottombar_tv_report);
            videoReportRela = rootView.findViewById(R.id.bottombar_rela_report);
            videoLikeImg = rootView.findViewById(R.id.bottombar_img_like);
            videoLikeTv = rootView.findViewById(R.id.bottombar_tv_like);
            videoLikeRela = rootView.findViewById(R.id.bottombar_rela_like);
            videoTransmitImg = rootView.findViewById(R.id.bottombar_img_transmit);
            videoTransmitTv = rootView.findViewById(R.id.bottombar_tv_transmit);
            videoTransmitRela = rootView.findViewById(R.id.bottombar_rela_transmit);
            videoRewardImg = rootView.findViewById(R.id.bottombar_img_reward);
            videoRewardTv = rootView.findViewById(R.id.bottombar_tv_reward);
            videoReward = rootView.findViewById(R.id.bottombar_rela_reward);
            videoCommentImg = rootView.findViewById(R.id.bottombar_img_comment);
            videoCommentTv = rootView.findViewById(R.id.bottombar_tv_comment);
            videoCommentRela = rootView.findViewById(R.id.bottombar_rela_comment);
            ll_topbar = rootView.findViewById(R.id.app_video_top_box);
            ll_bottombar = rootView.findViewById(R.id.ll_bottom_bar);
            iv_trumb =rootView.findViewById(R.id.iv_trumb);
            videoPause = rootView.findViewById(R.id.video_pause_rela);
            bottomView = rootView.findViewById(R.id.popup_rela);
            bottomBarEt = rootView.findViewById(R.id.popup_comment_et);
            bottomBarCancle = rootView.findViewById(R.id.popup_cancle_img);
            mHeartGroup=rootView.findViewById(R.id.heart_group);
        }
        //设置所有按钮的点击事件
        videoAddImg.setOnClickListener(onClickListener);
        videoBackImg .setOnClickListener(onClickListener);
        videoAttention .setOnClickListener(onClickListener);
        videoHeadImg .setOnClickListener(onClickListener);
        videoAttentionRela.setOnClickListener(onClickListener);
        videoReportImg.setOnClickListener(onClickListener);
        videoReportTv .setOnClickListener(onClickListener);
        videoReportRela .setOnClickListener(onClickListener);
        videoLikeImg .setOnClickListener(onClickListener);
        videoLikeTv.setOnClickListener(onClickListener);
        videoLikeRela .setOnClickListener(onClickListener);
        videoTransmitImg .setOnClickListener(onClickListener);
        videoTransmitTv .setOnClickListener(onClickListener);
        videoTransmitRela .setOnClickListener(onClickListener);
        videoRewardImg .setOnClickListener(onClickListener);
        videoRewardTv .setOnClickListener(onClickListener);
        videoReward .setOnClickListener(onClickListener);
        videoCommentImg .setOnClickListener(onClickListener);
        videoCommentTv .setOnClickListener(onClickListener);
        videoCommentRela.setOnClickListener(onClickListener);
        bottomBarEt.setOnClickListener(onClickListener);
        bottomBarCancle.setOnClickListener(onClickListener);
        mHeartGroup.setListener(this);
        bottomBarEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                if(b){
                    timer.schedule(new TimerTask() {
                        public void run() {
                            //调用键盘
                            KeybordS.openKeybord(shapeEt,mActivity);

                        }
                    }, 200);
                    if(slide!=null){
                        slide.showPopupWindow();
                        Log.d("comment1","show");
                    }else {
                        selectComment();
                    }
                    slide.judgeKeybord(mContext);

                }

            }
        });
        bottomBarEt.setInputType(InputType.TYPE_NULL);
        query.id(R.id.app_video_netTie_icon).clicked(onClickListener);
        query.id(R.id.app_video_replay_icon).clicked(onClickListener);
        videoView.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(IMediaPlayer mp, int what, int extra) {
                if (what == PlayStateParams.MEDIA_INFO_NETWORK_BANDWIDTH || what == PlayStateParams.MEDIA_INFO_BUFFERING_BYTES_UPDATE) {
                    Log.e("", "dou361.====extra=======" + extra);
                }
                statusChange(what);
                if (onInfoListener != null) {
                    onInfoListener.onInfo(mp, what, extra);
                }
                return true;
            }
        });
        this.streamSelectAdapter = new StreamSelectAdapter(mContext, listVideos);
          initHeight = rl_box.getLayoutParams().height;
        hideAll();
        if (!playerSupport) {
            showStatus(mActivity.getResources().getString(R.string.not_support));
        } else {
        }


        //videopause滑动监听
        videoPause.setOnTouchListener(this);


    }
    public static int getStatusBarHeight(Activity a) {
        int result = 0;
        int resourceId = a.getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = a.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**==========================================Activity生命周期方法回调=============================*/
    public PlayerView onPause() {
        bgState = (videoView.isPlaying() ? 0 : 1);
        getCurrentPosition();
        videoView.onPause();
        return this;
    }

    public PlayerView onResume() {
        videoView.onResume();
        if (isLive) {
            videoView.seekTo(0);
        } else {
            videoView.seekTo(currentPosition);
        }
        if (bgState == 0) {

        } else {
            pausePlay();
        }
        return this;
    }

    public PlayerView onDestroy() {
        mHandler.removeMessages(MESSAGE_RESTART_PLAY);
        videoView.stopPlayback();
        return this;
    }

    public PlayerView onConfigurationChanged(final Configuration newConfig) {
        isPortrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
        return this;
    }

    public boolean onBackPressed() {
        if (!isOnlyFullScreen && getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            return true;
        }
        return false;
    }

    /**
     * ==========================================Activity生命周期方法回调=============================
     */

    /**
     * ==========================================对外的方法=============================
     */


    /**
     * 显示缩略图
     */
    public PlayerView showThumbnail(OnShowThumbnailListener onShowThumbnailListener) {
        this.mOnShowThumbnailListener = onShowThumbnailListener;
        if (mOnShowThumbnailListener != null && iv_trumb != null) {
            mOnShowThumbnailListener.onShowThumbnail(iv_trumb);
        }
        return this;
    }

    /**
     * 设置播放信息监听回调
     */
    public PlayerView setOnInfoListener(IMediaPlayer.OnInfoListener onInfoListener) {
        this.onInfoListener = onInfoListener;
        return this;
    }

    /**
     * 设置播放器中的返回键监听
     */
    public PlayerView setPlayerBackListener(OnPlayerBackListener listener) {
        this.mPlayerBack = listener;
        return this;
    }
    /**
     * 设置跳转页面
     *
     */
    public PlayerView intentActivity(Class activity){
        this.secActivity=activity;
        return this;
    }
    public PlayerView intentActivitythi(Class activity){
        this.thiActivity=activity;
        return this;
    }

    /**
     * 设置控制面板显示隐藏监听
     */
    public PlayerView setOnControlPanelVisibilityChangListenter(OnControlPanelVisibilityChangeListener listener) {
        this.onControlPanelVisibilityChangeListener = listener;
        return this;
    }

    /**
     * 百分比显示切换
     */
    public PlayerView toggleAspectRatio() {
        if (videoView != null) {
            videoView.toggleAspectRatio();
        }
        return this;
    }

    /**
     * 设置播放区域拉伸类型
     */
    public PlayerView setScaleType(int showType) {
        currentShowType = showType;
        videoView.setAspectRatio(currentShowType);
        return this;
    }

    /**
     * 旋转角度
     */
    public PlayerView setPlayerRotation() {
        if (rotation == 0) {
            rotation = 90;
        } else if (rotation == 90) {
            rotation = 270;
        } else if (rotation == 270) {
            rotation = 0;
        }
        setPlayerRotation(rotation);
        return this;
    }

    /**
     * 旋转指定角度
     */
    public PlayerView setPlayerRotation(int rotation) {
        if (videoView != null) {
            videoView.setPlayerRotation(rotation);
            videoView.setAspectRatio(currentShowType);
        }
        return this;
    }

    /**
     * 设置播放地址
     * 包括视频清晰度列表
     * 对应地址列表
     */
    public PlayerView setPlaySource(List<VideoijkBean> list) {
        listVideos.clear();
        if (list != null && list.size() > 0) {
            listVideos.addAll(list);
            switchStream(0);
        }
        return this;
    }

    /**
     * 设置播放地址
     * 单个视频VideoijkBean
     */
    public PlayerView setPlaySource(VideoijkBean videoijkBean) {
        listVideos.clear();
        if (videoijkBean != null) {
            listVideos.add(videoijkBean);
            switchStream(0);
        }
        return this;
    }

    /**
     * 设置播放地址
     * 单个视频地址时
     * 带流名称
     */
    public PlayerView setPlaySource(String stream, String url) {
        VideoijkBean mVideoijkBean = new VideoijkBean();
        mVideoijkBean.setStream(stream);
        mVideoijkBean.setUrl(url);
        setPlaySource(mVideoijkBean);
        return this;
    }

    /**
     * 设置播放地址
     * 单个视频地址时
     */
    public PlayerView setPlaySource(String url) {
        setPlaySource("标清", url);
        return this;
    }

    /**
     * 自动播放
     */
    public PlayerView autoPlay(String path) {
        setPlaySource(path);
        startPlay();
        return this;
    }

    /**
     * 开始播放
     */
    public PlayerView startPlay() {
        if (isLive) {
            videoView.setVideoPath(currentUrl);
            videoView.seekTo(0);
        } else {
            if (isHasSwitchStream || status == PlayStateParams.STATE_ERROR) {
                //换源之后声音可播，画面卡住，主要是渲染问题，目前只是提供了软解方式，后期提供设置方式
                videoView.setRender(videoView.RENDER_TEXTURE_VIEW);
                videoView.setVideoPath(currentUrl);
                videoView.seekTo(currentPosition);
                isHasSwitchStream = false;
            }
        }
        hideStatusUI();
        if (isGNetWork && (NetworkUtils.getNetworkType(mContext) == 4 || NetworkUtils.getNetworkType(mContext) == 5 || NetworkUtils.getNetworkType(mContext) == 6)) {
            query.id(R.id.app_video_netTie).visible();
        } else {
            if (isCharge && maxPlaytime < getCurrentPosition()) {

            } else {
                if (playerSupport) {
                    query.id(R.id.app_video_loading).visible();
                    videoView.start();
                } else {
                    showStatus(mActivity.getResources().getString(R.string.not_support));
                }
            }
        }
        return this;
    }

    /**
     * 设置视频名称
     */
    public PlayerView setTitle(String title) {
        query.id(R.id.app_video_title).text(title);
        return this;
    }

    /**
     * 设置主播是否被关注
     */
    public PlayerView setAttention(boolean status) {
        isAttentionStatus=status;
        return this;
    }
    /**
     * 选择要播放的流
     */
    public PlayerView switchStream(int index) {
        if (listVideos.size() > index) {
            currentUrl = listVideos.get(index).getUrl();
            listVideos.get(index).setSelect(true);
            isLive();
            if (videoView.isPlaying()) {
                getCurrentPosition();
                videoView.release(false);
            }
            isHasSwitchStream = true;
        }
        return this;
    }

    /**
     * 暂停播放
     */
    public PlayerView pausePlay() {
        status = PlayStateParams.STATE_PAUSED;
        getCurrentPosition();
        videoView.pause();
        return this;
    }

    /**
     * 停止播放
     */
    public PlayerView stopPlay() {
        videoView.stopPlayback();
        isErrorStop = true;
        if (mHandler != null) {
            mHandler.removeMessages(MESSAGE_RESTART_PLAY);
        }
        return this;
    }

    /**
     * 设置播放位置
     */
    public PlayerView seekTo(int playtime) {
        videoView.seekTo(playtime);
        return this;
    }

    /**
     * 获取当前播放位置
     */
    public int getCurrentPosition() {
        if (!isLive) {
            currentPosition = videoView.getCurrentPosition();
        } else {
            /**直播*/
            currentPosition = -1;
        }
        return currentPosition;
    }

    /**
     * 获取视频播放总时长
     */
    public long getDuration() {
        duration = videoView.getDuration();
        return duration;
    }

    /**
     * 设置2/3/4/5G和WiFi网络类型提示，
     *
     * @param isGNetWork true为进行2/3/4/5G网络类型提示
     *                   false 不进行网络类型提示
     */
    public PlayerView setNetWorkTypeTie(boolean isGNetWork) {
        this.isGNetWork = isGNetWork;
        return this;
    }

    /**
     * 设置最大观看时长
     *
     * @param isCharge    true为收费 false为免费即不做限制
     * @param maxPlaytime 最大能播放时长，单位秒
     */
    public PlayerView setChargeTie(boolean isCharge, int maxPlaytime) {
        this.isCharge = isCharge;
        this.maxPlaytime = maxPlaytime * 1000;
        return this;
    }


    /**
     * 是否仅仅为全屏
     */
    public PlayerView setOnlyFullScreen(boolean isFull) {
        this.isOnlyFullScreen = isFull;
        tryFullScreen(isOnlyFullScreen);
        if (isOnlyFullScreen) {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }
        return this;
    }

    /**
     * 设置是否禁止双击
     */
    public PlayerView setForbidDoulbeUp(boolean flag) {
        this.isForbidDoulbeUp = flag;
        return this;
    }
    /**\
     *设置当前地评论窗口是否弹出
     */
    public PlayerView setPopUp(boolean popUp){
        this.isPopUp=popUp;
        return this;
    }
    /**
     * 获取当前评论窗口的弹出状态
     */
    public boolean getPopUp(){
        return isPopUp;
    }

    /**
     * 当前播放的是否是直播
     */
    public boolean isLive() {
        if (currentUrl != null
                && (currentUrl.startsWith("rtmp://")
                || (currentUrl.startsWith("http://") && currentUrl.endsWith(".m3u8"))
                || (currentUrl.startsWith("http://") && currentUrl.endsWith(".flv")))) {
            isLive = true;
        } else {
            isLive = false;
        }
        return isLive;
    }

    /**
     * 是否禁止触摸
     */
    public PlayerView forbidTouch(boolean forbidTouch) {
        this.isForbidTouch = forbidTouch;
        return this;
    }

    /**
     * 隐藏所有状态界面
     */
    public PlayerView hideAllUI() {
        if (query != null) {
            hideAll();
        }
        return this;
    }

    /**
     * 获取顶部控制barview
     */
    public View getTopBarView() {
        return ll_topbar;
    }

    /**
     * 获取底部控制barview
     */
    public View getBottonBarView() {
        return ll_bottombar;
    }



    /**
     * 获取返回view
     */
    public ImageView getBackView() {
        return videoBackImg;
    }

    /**
     * 获取菜单view
     */
    public RelativeLayout getMenuView() {
        return videoAttentionRela;
    }


    /**
     * 设置当前用户的喜好
     */
    public PlayerView setLikeStatus(boolean isLike){
        this.isLike=isLike;
        return this;
    }
    /**
     * 获取当前用户的喜好
     */
    public boolean getLikeStatus(){
        return isLike;
    }
    /**
     * 获取中间的播放view
     */
    public ImageView getPlayerView() {
        return videoPlayIcon;
    }

    /**
     * 隐藏返回键，true隐藏，false为显示
     */
    public PlayerView hideBack(boolean isHide) {
        videoBackImg.setVisibility(isHide ? View.GONE : View.VISIBLE);
        return this;
    }

    /**
     * 隐藏菜单键，true隐藏，false为显示
     */
    public PlayerView hideMenu(boolean isHide) {
        videoAttentionRela.setVisibility(isHide ? View.GONE : View.VISIBLE);
        return this;
    }

    /**
     * 隐藏中间播放按钮,ture为隐藏，false为不做隐藏处理，但不是显示
     */
    public PlayerView hideCenterPlayer(boolean isHide) {
        isHideCenterPlayer = isHide;
        videoPlayIcon.setVisibility(isHideCenterPlayer ? View.GONE : View.VISIBLE);
        return this;
    }

    /**
     * 是否隐藏topbar，true为隐藏，false为不隐藏，但不一定是显示
     */
    public PlayerView hideHideTopBar(boolean isHide) {
        isHideTopBar = isHide;
        ll_topbar.setVisibility(isHideTopBar ? View.GONE : View.VISIBLE);
        return this;
    }

    /**
     * 是否隐藏bottonbar，true为隐藏，false为不隐藏，但不一定是显示
     */
    public PlayerView hideBottonBar(boolean isHide) {
        /*
      是否隐藏bottonbar，true为隐藏，false为不隐藏
     */
        boolean isHideBottonBar = isHide;
        ll_bottombar.setVisibility(isHideBottonBar ? View.GONE : View.VISIBLE);
        return this;
    }

    /**
     * 是否隐藏上下bar，true为隐藏，false为不隐藏，但不一定是显示
     */
    public PlayerView hideControlPanl(boolean isHide) {
        hideBottonBar(isHide);
        hideHideTopBar(isHide);
        return this;
    }

    /**
     * 设置自动重连的模式或者重连时间，isAuto true 出错重连，false出错不重连，connectTime重连的时间
     */
    public PlayerView setAutoReConnect(boolean isAuto, int connectTime) {
        this.isAutoReConnect = isAuto;
        this.autoConnectTime = connectTime;
        return this;
    }

    /**
     * 显示或隐藏操作面板
     */
    public PlayerView operatorPanl() {
        isShowControlPanl = !isShowControlPanl;
        if (isShowControlPanl) {
            if (isLive) {
                query.id(R.id.app_video_process_panl).invisible();
            } else {
                query.id(R.id.app_video_process_panl).visible();
            }
            if (onControlPanelVisibilityChangeListener != null) {
                onControlPanelVisibilityChangeListener.change(true);
            }
            /**显示面板的时候再根据状态显示播放按钮*/
            if (status == PlayStateParams.STATE_PLAYING
                    || status == PlayStateParams.STATE_PREPARED
                    || status == PlayStateParams.STATE_PREPARING
                    || status == PlayStateParams.STATE_PAUSED) {
                if (isHideCenterPlayer) {
                    videoPlayIcon.setVisibility(View.GONE);
                } else {
                    videoPlayIcon.setVisibility(isLive ? View.VISIBLE : View.GONE);
                }
            } else {
                videoPlayIcon.setVisibility(View.VISIBLE);
            }
            updatePausePlay();
            mAutoPlayRunnable.start();
        } else {

            if (!isLive && status == PlayStateParams.STATE_PAUSED && !videoView.isPlaying()) {
                if (isHideCenterPlayer) {
                    videoPlayIcon.setVisibility(View.GONE);
                } else {
                    /**暂停时一直显示按钮*/
                    videoPlayIcon.setVisibility(View.VISIBLE);
                }
            } else {
                videoPlayIcon.setVisibility(View.GONE);
            }
            if (onControlPanelVisibilityChangeListener != null) {
                onControlPanelVisibilityChangeListener.change(false);
            }
            mAutoPlayRunnable.stop();
        }
        return this;
    }

    /**
     * 全屏切换
     *
     */
    public PlayerView toggleFullScreen(MotionEvent e) {

        mHeartGroup.setVisibility(View.VISIBLE);
        //根据点击次数来决定喜欢的增长次数
        isLike=false;
        selectLikeButton();


        return this;
    }

    /**
     * 显示菜单设置
     */
    public PlayerView showMenu() {

        if(!isAttentionStatus){
            startPropertyAnim();
            isAttentionStatus=!isAttentionStatus;

        }else {
            videoAddImg.setVisibility(View.GONE);
            videoAttention.setVisibility(View.GONE);
            reduce();
            isAttentionStatus=!isAttentionStatus;
        }


        return this;
    }
    /**
     * 更改主播当前状态
     */
    public boolean getAttentionStatus(){
        return isAttentionStatus;
    }
    // 动画实际执行
    public void startPropertyAnim() {
        videoAddImg.setVisibility(View.GONE);
        videoAttention.setVisibility(View.GONE);
    }
    // 动画实际执行
    public void reduce() {

        LayoutTransition transition = new LayoutTransition();
        transition.setAnimator(LayoutTransition.CHANGE_APPEARING,
                null);
        videoAddImg.setVisibility(View.VISIBLE);
        videoAttention.setVisibility(View.VISIBLE);
        videoAttentionRela.setLayoutTransition(transition);
    }

    /**
     * 进度条和时长显示的方向切换
     */
    public PlayerView toggleProcessDurationOrientation() {
        setProcessDurationOrientation(PlayStateParams.PROCESS_PORTRAIT);
        return this;
    }

    /**
     * 设置进度条和时长显示的方向，默认为上下显示，true为上下显示false为左右显示
     */
    public PlayerView setProcessDurationOrientation(int portrait) {
        if (portrait == PlayStateParams.PROCESS_CENTER) {
            query.id(R.id.app_video_currentTime_full).gone();
            query.id(R.id.app_video_endTime_full).gone();
            query.id(R.id.app_video_center).gone();
            query.id(R.id.app_video_lift).visible();
        } else if (portrait == PlayStateParams.PROCESS_LANDSCAPE) {
            query.id(R.id.app_video_currentTime_full).visible();
            query.id(R.id.app_video_endTime_full).visible();
            query.id(R.id.app_video_center).gone();
            query.id(R.id.app_video_lift).gone();
        } else {
            query.id(R.id.app_video_currentTime_full).gone();
            query.id(R.id.app_video_endTime_full).gone();
            query.id(R.id.app_video_center).visible();
            query.id(R.id.app_video_lift).gone();
        }
        return this;
    }


    /**
     * 获取界面方向
     */
    public int getScreenOrientation() {
        int rotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
        DisplayMetrics dm = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        int orientation;
        // if the device's natural orientation is portrait:
        if ((rotation == Surface.ROTATION_0
                || rotation == Surface.ROTATION_180) && height > width ||
                (rotation == Surface.ROTATION_90
                        || rotation == Surface.ROTATION_270) && width > height) {
            switch (rotation) {
                case Surface.ROTATION_0:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
                case Surface.ROTATION_90:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
                case Surface.ROTATION_180:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                    break;
                case Surface.ROTATION_270:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                    break;
                default:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
            }
        }
        // if the device's natural orientation is landscape or if the device
        // is square:
        else {
            switch (rotation) {
                case Surface.ROTATION_0:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
                case Surface.ROTATION_90:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    break;
                case Surface.ROTATION_180:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                    break;
                case Surface.ROTATION_270:
                    orientation =
                            ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                    break;
                default:
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    break;
            }
        }

        return orientation;
    }

    /**
     * ==========================================对外的方法=============================
     */

    /**
     * ==========================================内部方法=============================
     */


    /**
     * 状态改变同步UI
     */
    private void statusChange(int newStatus) {
        if (newStatus == PlayStateParams.STATE_COMPLETED) {
            status = PlayStateParams.STATE_PLAYING;
            currentPosition = 0;
            hideAll();
            startPlay();
            //showStatus("播放结束");
        } else if (newStatus == PlayStateParams.STATE_PREPARING
                || newStatus == PlayStateParams.MEDIA_INFO_BUFFERING_START) {
            status = PlayStateParams.STATE_PREPARING;
            /**视频缓冲*/
            hideStatusUI();
            query.id(R.id.app_video_loading).visible();
        } else if (newStatus == PlayStateParams.MEDIA_INFO_VIDEO_RENDERING_START
                || newStatus == PlayStateParams.STATE_PLAYING
                || newStatus == PlayStateParams.STATE_PREPARED
                || newStatus == PlayStateParams.MEDIA_INFO_BUFFERING_END
                || newStatus == PlayStateParams.STATE_PAUSED) {
            if (status == PlayStateParams.STATE_PAUSED) {
                status = PlayStateParams.STATE_PAUSED;
            } else {
                status = PlayStateParams.STATE_PLAYING;
            }
            /**视频缓冲结束后隐藏缩列图*/
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    hideStatusUI();
                    /**显示控制bar*/
                    isShowControlPanl = false;
                    if (!isForbidTouch) {
                        operatorPanl();
                    }
                    /**延迟0.5秒隐藏视频封面隐藏*/
                    query.id(R.id.ll_bg).gone();
                }
            }, 500);
        } else if (newStatus == PlayStateParams.MEDIA_INFO_VIDEO_INTERRUPT) {
            /**直播停止推流*/
            status = PlayStateParams.STATE_ERROR;
            if (!(isGNetWork &&
                    (NetworkUtils.getNetworkType(mContext) == 4
                            || NetworkUtils.getNetworkType(mContext) == 5
                            || NetworkUtils.getNetworkType(mContext) == 6))) {
                if (isCharge && maxPlaytime < getCurrentPosition()) {
                } else {
                    hideAll();
                    if (isLive) {
                        showStatus("获取不到直播源");
                    } else {
                        showStatus(mActivity.getResources().getString(R.string.small_problem));
                    }
                    /**5秒尝试重连*/
                    if (!isErrorStop && isAutoReConnect) {
                        mHandler.sendEmptyMessageDelayed(MESSAGE_RESTART_PLAY, autoConnectTime);
                    }

                }
            } else {
                query.id(R.id.app_video_netTie).visible();
            }

        } else if (newStatus == PlayStateParams.STATE_ERROR
                || newStatus == PlayStateParams.MEDIA_INFO_UNKNOWN
                || newStatus == PlayStateParams.MEDIA_ERROR_IO
                || newStatus == PlayStateParams.MEDIA_ERROR_MALFORMED
                || newStatus == PlayStateParams.MEDIA_ERROR_UNSUPPORTED
                || newStatus == PlayStateParams.MEDIA_ERROR_TIMED_OUT
                || newStatus == PlayStateParams.MEDIA_ERROR_SERVER_DIED) {
            status = PlayStateParams.STATE_ERROR;
            if (!(isGNetWork && (NetworkUtils.getNetworkType(mContext) == 4 || NetworkUtils.getNetworkType(mContext) == 5 || NetworkUtils.getNetworkType(mContext) == 6))) {
                if (isCharge && maxPlaytime < getCurrentPosition()) {
                } else {
                    hideStatusUI();
                    if (isLive) {
                        showStatus(mActivity.getResources().getString(R.string.small_problem));
                    } else {
                        showStatus(mActivity.getResources().getString(R.string.small_problem));
                    }
                    /**5秒尝试重连*/
                    if (!isErrorStop && isAutoReConnect) {
                        mHandler.sendEmptyMessageDelayed(MESSAGE_RESTART_PLAY, autoConnectTime);
                    }
                }
            } else {
                query.id(R.id.app_video_netTie).visible();
            }
        }
    }

    /**
     * 显示视频播放状态提示
     */
    private void showStatus(String statusText) {
        query.id(R.id.app_video_replay).visible();
        query.id(R.id.app_video_status_text).text(statusText);
    }


    /**
     * 设置界面方向
     */
    private void setFullScreen(boolean fullScreen) {
        if (mActivity != null) {
            WindowManager.LayoutParams attrs = mActivity.getWindow().getAttributes();
            if (fullScreen) {
                attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
                mActivity.getWindow().setAttributes(attrs);
                mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            } else {
                attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                mActivity.getWindow().setAttributes(attrs);
                mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
            toggleProcessDurationOrientation();
        }

    }

    /**
     * 设置界面方向带隐藏actionbar
     */
    private void tryFullScreen(boolean fullScreen) {
        if (mActivity instanceof AppCompatActivity) {
            ActionBar supportActionBar = ((AppCompatActivity) mActivity).getSupportActionBar();
            if (supportActionBar != null) {
                if (fullScreen) {
                    supportActionBar.hide();
                } else {
                    supportActionBar.show();
                }
            }
        }
        setFullScreen(fullScreen);
    }


    /**
     * 隐藏状态界面
     */
    private void hideStatusUI() {
        videoPlayIcon.setVisibility(View.GONE);
        query.id(R.id.app_video_replay).gone();
        query.id(R.id.app_video_netTie).gone();
        query.id(R.id.app_video_loading).gone();
        if (onControlPanelVisibilityChangeListener != null) {
            onControlPanelVisibilityChangeListener.change(false);
        }
    }

    /**
     * 隐藏所有界面
     */
    private void hideAll() {
        hideStatusUI();
    }

    /**
     * 显示分辨率列表
     */
    private void showStreamSelectView() {
    }

    /**
     * 隐藏分辨率列表
     */
    private void hideStreamSelectView() {
    }

    /**
     * 更新播放、暂停和停止按钮
     */
    private void updatePausePlay() {
        if (isPlaying) {
                videoPlayIcon.setImageResource(R.drawable.simple_player_center_pause);

        } else {
            videoPlayIcon.setImageResource(R.drawable.simple_player_center_play);
        }
    }


    /**
     * 滑动改变声音大小
     *
     * @param percent
     */
    private void onVolumeSlide(float percent) {
        if (volume == -1) {
            volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (volume < 0)
                volume = 0;
        }
        int index = (int) (percent * mMaxVolume) + volume;
        if (index > mMaxVolume)
            index = mMaxVolume;
        else if (index < 0)
            index = 0;

        // 变更声音
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

        // 变更进度条
        int i = (int) (index * 1.0 / mMaxVolume * 100);
        String s = i + "%";
        if (i == 0) {
            s = "off";
        }
        // 显示
        query.id(R.id.app_video_volume_icon).image(i == 0 ? R.drawable.simple_player_volume_off_white_36dp : R.drawable.simple_player_volume_up_white_36dp);
        query.id(R.id.app_video_brightness_box).gone();
        query.id(R.id.app_video_volume_box).visible();
        query.id(R.id.app_video_volume_box).visible();
        query.id(R.id.app_video_volume).text(s).visible();
    }
    //监听软键盘弹起
    @Override
    public void onKeyPop() {

    }
    //监听软键盘隐藏
    @Override
    public void onKeyHide() {
        slide.dismiss();
    }


    //设置屏幕双击事件的动画
    private void setAnimImg(final ImageView img, float x, float y) {
        ObjectAnimator scaleX=ObjectAnimator.ofFloat(img, "scaleX", 1f, 1.5f,2f);
        ObjectAnimator scaleY=ObjectAnimator.ofFloat(img, "scaleY", 1f, 1.5f,2f);
        ObjectAnimator alpha=ObjectAnimator.ofFloat(img,"alpha",1f,0.5f,0f);
        ObjectAnimator trans=ObjectAnimator.ofFloat(img,"translationY",y,y-img.getHeight()*2);
        ObjectAnimator transX=ObjectAnimator.ofFloat(img,"translationX",x,x-img.getWidth());
        AnimatorSet set=new AnimatorSet();
        set.play(scaleX).with(scaleY).with(alpha).with(trans).with(transX);
        set.setDuration(500);
        set.start();
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                videoPause.removeView(img);

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
    }

    @Override
    public void onAnimEnd() {

        isForbidDoulbeUp=false;


    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()){
        case MotionEvent.ACTION_DOWN:
            mLastTime=mCurTime;
            mCurTime= System.currentTimeMillis();
            final float x = motionEvent.getX();
            final float y = motionEvent.getY();
            mInitialMotionX = x;
            mInitialMotionY = y;
            if(mCurTime-mLastTime<200){//双击事件
                mCurTime =0;
                mLastTime = 0;
                mHandler.removeMessages(MESSAGE_ONSINGLE_CLICK);
                Message msg=Message.obtain();
                msg.what=MESSAGE_ONDOUBLE_CLICK;
                //msg.obj=motionEvent;
                isForbidDoulbeUp=true;
                mHandler.sendMessage(msg);
            }else{//单击事件
                isForbidDoulbeUp=false;
                mHandler.removeMessages(MESSAGE_ONSINGLE_CLICK);
                mHandler.sendEmptyMessageDelayed(MESSAGE_ONSINGLE_CLICK,320);
            }
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            final float upX = motionEvent.getX();
            final float upY= motionEvent.getY();
            final float dx = upX - mInitialMotionX;
            final float dy = upY - mInitialMotionY;
            Log.d("zzz","open");
            if(Math.abs(dx)>Math.abs(dy)) {
                if (dx > 0) {
                    Intent intent = new Intent(mActivity, secActivity);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.trans_left_in, R.anim.trans_right_out);
                } else {
                    Intent intent = new Intent(mActivity, thiActivity);
                    mActivity.startActivity(intent);
                    mActivity.overridePendingTransition(R.anim.tran_in, R.anim.tran_out);
                }
                return true;
            }else {
                return false;
            }

    }
        return true;


    }


    /**
     * ==========================================内部方法=============================
     */


    /**
     * ==========================================内部类=============================
     */

    /**
     * 收起控制面板轮询，默认5秒无操作，收起控制面板，
     */
    private class AutoPlayRunnable implements Runnable {
        private int AUTO_PLAY_INTERVAL = 5000;
        private boolean mShouldAutoPlay;

        /**
         * 五秒无操作，收起控制面板
         */
        public AutoPlayRunnable() {
            mShouldAutoPlay = false;
        }

        public void start() {
            if (!mShouldAutoPlay) {
                mShouldAutoPlay = true;
                mHandler.removeCallbacks(this);
                mHandler.postDelayed(this, AUTO_PLAY_INTERVAL);
            }
        }

        public void stop() {
            if (mShouldAutoPlay) {
                mHandler.removeCallbacks(this);
                mShouldAutoPlay = false;
            }
        }

        @Override
        public void run() {
            if (mShouldAutoPlay) {
                mHandler.removeCallbacks(this);
                if (!isForbidTouch && !isShowControlPanl) {
                    operatorPanl();
                }
            }
        }
    }

    /**
     * 播放器的手势监听
     */
    public class PlayerGestureListener extends GestureDetector.SimpleOnGestureListener {

        /**
         * 是否是按下的标识，默认为其他动作，true为按下标识，false为其他动作
         */
        private boolean isDownTouch;
        /**
         * 是否声音控制,默认为亮度控制，true为声音控制，false为亮度控制
         */
        private boolean isVolume;
        /**
         * 是否横向滑动，默认为纵向滑动，true为横向滑动，false为纵向滑动
         */
        private boolean isLandscape;

        /**
         * 双击
         */
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            /**视频视窗双击事件*/
            if (!isForbidTouch && !isOnlyFullScreen && !isForbidDoulbeUp) {
            }
            return true;
        }

        /**
         * 按下
         */
        @Override
        public boolean onDown(MotionEvent e) {
            isDownTouch = true;
            return super.onDown(e);
        }


        /**
         * 滑动
         */
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if (!isForbidTouch) {
                float mOldX = e1.getX(), mOldY = e1.getY();
                float deltaY = mOldY - e2.getY();
                float deltaX = mOldX - e2.getX();
                if (isDownTouch) {
                    isLandscape = Math.abs(distanceX) >= Math.abs(distanceY);
                    isVolume = mOldX > screenWidthPixels * 0.5f;
                    isDownTouch = false;
                }

                if (isLandscape) {
                    if (!isLive) {
                    }
                } else {
                    float percent = deltaY / videoView.getHeight();


                }
            }
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        /**
         * 单击
         */
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            /**视频视窗单击事件*/

            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return super.onSingleTapConfirmed(e);
        }
    }

}
